import threading

import pandas as pd
import jieba
import requests
import os
import re
import json
from concurrent.futures import ThreadPoolExecutor
from queue import Queue
from Baidu_Text_transAPI import translate

# 创建一个锁对象
lock = threading.Lock()


def is_valid_word(word):
    """检查词语是否有效（不为空且不仅仅包含符号）"""
    return bool(re.search(r'\b\w+\b', word))


def translate_word(word):
    """翻译单词，优先使用本地字典"""
    if word not in translation_dict:
        translated = translate(word)
        translation_dict[word] = translated
        # 动态保存字典
        with open(translation_dict_path, "w", encoding="utf-8") as file:
            json.dump(translation_dict, file, ensure_ascii=False, indent=4)
    return translation_dict[word]


def process_row(index):
    row = df.iloc[index]
    # 尝试下载图片
    image_url = row["图片地址"]
    image_file_path = f"downloads/{index + 1}.jpg"
    response = requests.get(image_url)
    try:
        with open(image_file_path, "wb") as file:
            file.write(response.content)
    except:
        print(f"Error downloading {image_url}: Status code {response.status_code}")
        return

    # 分词处理
    words = jieba.cut(row["商品名称"], cut_all=False)
    # 翻译每个有效词
    translated_words = [translate_word(word) for word in words if is_valid_word(word)]
    # 使用逗号和空格连接词语
    words_text = ", ".join(translated_words)
    # 保存分词结果到TXT文件
    txt_file_path = f"downloads/{index + 1}.txt"
    with open(txt_file_path, "w", encoding="utf-8") as file:
        file.write(words_text)
    # 打印结果
    print("第{}行处理完毕！".format(index))



if __name__ == '__main__':
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36'
    }
    # 读取Excel文件
    df = pd.read_excel("../data/商品信息(带图片).xlsx")  # 替换为您的Excel文件路径
    total_rows = len(df)
    # 确保目录存在
    os.makedirs('downloads', exist_ok=True)
    # 加载或创建本地翻译字典
    translation_dict_path = "downloads/translation_dict.json"
    if os.path.exists(translation_dict_path):
        with open(translation_dict_path, "r", encoding="utf-8") as file:
            translation_dict = json.load(file)
    else:
        translation_dict = {}

    need_list = [14, 13, 16, 17, 18, 397, 12, 15]
    for i in need_list:
        process_row(i-1)

